package com.bigcat.gulimall.gulimallproduct.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigcat.gulimall.common.constant.ProductConstant;
import com.bigcat.gulimall.common.entry.SkuEsModel;
import com.bigcat.gulimall.common.utils.PageUtils;
import com.bigcat.gulimall.common.utils.Query;
import com.bigcat.gulimall.common.utils.R;
import com.bigcat.gulimall.gulimallproduct.dao.SpuInfoDao;
import com.bigcat.gulimall.gulimallproduct.entity.*;
import com.bigcat.gulimall.gulimallproduct.feign.SearchFeignService;
import com.bigcat.gulimall.gulimallproduct.feign.WareFeignService;
import com.bigcat.gulimall.gulimallproduct.service.*;
import com.bigcat.gulimall.gulimallproduct.vo.SkuHasStockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId
     * @return
     */
    @Override
    public boolean up(Long spuId) {
        //1.获得当前spu下所有的sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        //TODO 4.获得查询当前sku的所有可以被用来检索的属性
        List<ProductAttrValueEntity> baseAttrList = attrValueService.baseAttrListForSpu(spuId);
        //收集当前spu下的所有属性id
        List<Long> attrIdList = baseAttrList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        if (!(attrIdList.size() > 0)){
            return false;
        }
        //获得可被用来检索的属性id
        List<Long> searchAttrIds = attrService.selectSearchByAttrs(attrIdList);
        HashSet<Long> attrIdsSet = new HashSet<>(searchAttrIds);
        //获得存在的属性信息
        List<SkuEsModel.Attrs> attrsList = baseAttrList.stream().filter(baseAttr -> attrIdsSet.contains(baseAttr.getAttrId())
        ).map(baseAttr -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(baseAttr, attrs);
            return attrs;
        }).collect(Collectors.toList());
        //获得所的sku
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //TODO 1.发送请求，远程端端调用查询是否有库存
        //调用库存服务，获得库存信息,可能存在网络异常，调用失败，所以要try--catch
        Map<Long, Boolean> hasStockMap = null;
        try {
            R hasStock = wareFeignService.getHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            List<SkuHasStockVo> hasStockVoList = hasStock.getData(typeReference);
            hasStockMap = hasStockVoList.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));

        } catch (Exception e) {
            log.error("调用库存服务失败：{}", e);
        }
        //再lambda中使用变量需要时final的，所有要转化一下
        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        //2.封装每个sku信息
        List<SkuEsModel> skuEsModelList = skus.stream().map(skuInfoEntity -> {
            //组装es模型
            SkuEsModel skuEsModel = new SkuEsModel();
            //拷贝数据
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            //如果库存调用失败，默认有库存
            if (finalHasStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalHasStockMap.get(skuInfoEntity.getSkuId()));
            }

            //TODO 2.热度评分，这边有太多的算法，就不做详细的编码，默认设置为0
            skuEsModel.setHotScore(0L);
            //TODO 3.查询品牌的名字分类信息
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());
            //获得分类名
            CategoryEntity categoryEntity = categoryService.getById(skuInfoEntity.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5.将数据发送到ES保存 gulimall-search
        R result = searchFeignService.productStatusUp(skuEsModelList);
        if (result.getCode() == 0) {
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            //上架状态
            spuInfoEntity.setPublishStatus(ProductConstant.StatusEnum.UP_SPU.getCode());
            //更新商品状态
            baseMapper.update(spuInfoEntity, new QueryWrapper<SpuInfoEntity>().eq("id", spuId));
        } else {
            //TODO 重复调用，幂等性问题？ 重试机制？？
            log.error("ES同步失败");
            return false;
        }
        return true;

    }

}